package com.zjtaixue.o2o.web.shopadmin;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjtaixue.o2o.aspect.LogHttpInfo;
import com.zjtaixue.o2o.dto.ShopExecution;
import com.zjtaixue.o2o.entity.Area;
import com.zjtaixue.o2o.entity.PersonInfo;
import com.zjtaixue.o2o.entity.Shop;
import com.zjtaixue.o2o.entity.ShopCategory;
import com.zjtaixue.o2o.enums.ResultEnum;
import com.zjtaixue.o2o.enums.ShopStatusEnum;
import com.zjtaixue.o2o.service.AreaService;
import com.zjtaixue.o2o.service.ShopCategoryService;
import com.zjtaixue.o2o.service.ShopService;
import com.zjtaixue.o2o.util.*;
import com.zjtaixue.o2o.vo.ResultVO;
import jdk.nashorn.internal.runtime.logging.Logger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "/shopadmin")
@Slf4j
public class ShopManagementController {

    @Autowired
    private ShopService shopService;

    @Autowired
    private ShopCategoryService shopCategoryService;

    @Autowired
    private AreaService areaService;

    @GetMapping(value = "/getshopinitinfo")
    @ResponseBody
    public ResultVO getShopInitInfo(){
        Map<String,Object> modelMap=new HashMap<>();
        try {
            //获取所有的店铺列表信息
            List<ShopCategory> shopCategoryList=shopCategoryService.getShopCategoryList(new ShopCategory());
            List<Area> areaList=areaService.getAreaList();
            modelMap.put("shopCategoryList",shopCategoryList);
            modelMap.put("areaList",areaList);
        }catch (Exception e){
            return ResultVOUtil.error(ResultEnum.SYSTEM_UNKNOW_ERROR);
        }
        return ResultVOUtil.success(modelMap);
    }


    /**
     * 注册店铺
     * @param request
     * @return
     */
    @LogHttpInfo
    @PostMapping(value = "/registershop")
    @ResponseBody
    public ResultVO registerShop(HttpServletRequest request){
        //1.接受并转化相应的参数，包括店铺信息以及图片信息
        String shopStr= HttpServletRequestUtil.getString(request,"shopInfo");
        log.info("[注册的商店信息是]={}",shopStr);
        ObjectMapper mapper=new ObjectMapper();
        Shop shop=null;
        try{
            shop=mapper.readValue(shopStr,Shop.class);
        }catch (Exception e){
            return ResultVOUtil.error(ResultEnum.REGISTER_SHOP_FAIL);
        }
        CommonsMultipartFile shopImg=null;
        CommonsMultipartResolver resolver=new CommonsMultipartResolver(request.getSession().getServletContext());
        if(resolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest)request;
            shopImg=(CommonsMultipartFile)multipartHttpServletRequest.getFile("shopImg");
        }else{
            return ResultVOUtil.error(ResultEnum.IMAGE_IS_NULL);
        }
        //检查验证码是否正确
        if(!CodeUtil.checkVerifyCode(request)){
            return ResultVOUtil.error(ResultEnum.CHECKVERIFY_IS_WRONG);
        }
        //2.注册店铺
        if(shop!=null&&shopImg!=null){
            PersonInfo owner=(PersonInfo)request.getSession().getAttribute("user");
            shop.setOwnerId(owner.getUserId());
            try{
                ShopExecution shopExecution=shopService.addShop(shop,shopImg.getInputStream(),shopImg.getOriginalFilename());
                if(shopExecution.getCode()== ShopStatusEnum.CHECK.getCode()){
                    List<Shop> shopList=(List<Shop>)request.getSession().getAttribute("shopList");
                    if(shopList==null||shopList.size()==0){
                        shopList=new ArrayList<>();
                        shopList.add(shopExecution.getShop());
                    }
                    request.getSession().setAttribute("shopList",shopList);
                    return ResultVOUtil.success(shop);
                }
                else{
                    return ResultVOUtil.error(shopExecution.getCode(),shopExecution.getMsg());
                }
            }catch (Exception e){
                return ResultVOUtil.error(ResultEnum.IMAGE_CHANGE_FAIL);
            }
        }else{
            return ResultVOUtil.error(ResultEnum.SHOP_INFO_IS_NULL);
        }
    }

    /**
     * 修改店铺信息
     * @param request
     * @return
     */
    @LogHttpInfo
    @PostMapping(value = "/modifyshop")
    @ResponseBody
    public ResultVO modifyShop(HttpServletRequest request){
        //1.接受并转化相应的参数，包括店铺信息以及图片信息
        String shopStr= HttpServletRequestUtil.getString(request,"shopInfo");
        log.info("[修改的商店信息是]={}",shopStr);
        ObjectMapper mapper=new ObjectMapper();
        Shop shop=null;
        try{
            shop=mapper.readValue(shopStr,Shop.class);
        }catch (Exception e){
            return ResultVOUtil.error(ResultEnum.REGISTER_SHOP_FAIL);
        }
        CommonsMultipartFile shopImg=null;
        CommonsMultipartResolver resolver=new CommonsMultipartResolver(request.getSession().getServletContext());
        if(resolver.isMultipart(request)){
            MultipartHttpServletRequest multipartHttpServletRequest=(MultipartHttpServletRequest)request;
            shopImg=(CommonsMultipartFile)multipartHttpServletRequest.getFile("shopImg");
        }else{
            return ResultVOUtil.error(ResultEnum.IMAGE_IS_NULL);
        }
        //检查验证码是否正确
        if(!CodeUtil.checkVerifyCode(request)){
            return ResultVOUtil.error(ResultEnum.CHECKVERIFY_IS_WRONG);
        }
        //2.修改店铺信息
        if(shop!=null&&shop.getShopId()!=null){
            try{
                ShopExecution shopExecution=null;
                if(shopImg==null){
                    shopExecution=shopService.modifyShop(shop,null,null);
                }else{
                    shopExecution=shopService.modifyShop(shop,shopImg.getInputStream(),shopImg.getOriginalFilename());
                }
                if(shopExecution.getCode()== ShopStatusEnum.SUCCESS.getCode()){
                    return ResultVOUtil.success(shop);
                }
                else{
                    return ResultVOUtil.error(shopExecution.getCode(),shopExecution.getMsg());
                }
            }catch (Exception e){
                return ResultVOUtil.error(ResultEnum.IMAGE_CHANGE_FAIL);
            }
        }else{
            return ResultVOUtil.error(ResultEnum.SHOP_INFO_IS_NULL);
        }
    }


    /**
     * 通过店铺id获得店铺信息
     * @param request
     * @return
     */
    @LogHttpInfo
    @GetMapping(value = "/getshopbyid")
    @ResponseBody
    public ResultVO getShopById(HttpServletRequest request){
        Map<String,Object>modelMap=new HashMap<>();
        Long shopId=HttpServletRequestUtil.getLong(request,"shopId");
        try{
            if(shopId>-1){
                Shop shop=shopService.getByShopId(shopId);
                List<Area> areaList=areaService.getAreaList();
                modelMap.put("shop",shop);
                modelMap.put("areaList",areaList);
            }else{
                return ResultVOUtil.error(ResultEnum.QUERY_SHOP_IS_NULL);
            }
        }catch (Exception e){
            return ResultVOUtil.error(ResultEnum.SYSTEM_UNKNOW_ERROR);
        }
        return ResultVOUtil.success(modelMap);
    }

    /**
     * 分页查询店铺列表
     * @param request
     * @return
     */
    @LogHttpInfo
    @GetMapping(value="/getshoplist")
    @ResponseBody
    public ResultVO getShopList(HttpServletRequest request){
        Map<String,Object>modelMap=new HashMap<>();
        PersonInfo user=new PersonInfo();
        user.setUserId(1L);
        user.setName("---测试账号---");
        request.getSession().setAttribute("user",user);
        user=(PersonInfo) request.getSession().getAttribute("user");
        try{
            Shop shopCondition=new Shop();
            shopCondition.setOwner(user);
            ShopExecution shopExecution=shopService.getShopList(shopCondition,0,100);
            modelMap.put("shopList",shopExecution.getShopList());
            modelMap.put("user",user);
        }catch (Exception e){
            return ResultVOUtil.error(ResultEnum.SYSTEM_UNKNOW_ERROR);
        }
        return ResultVOUtil.success(modelMap);
    }

    @LogHttpInfo
    @GetMapping(value="/getshopmanagementinfo")
    @ResponseBody
    public ResultVO getShopManagementInfo(HttpServletRequest request){
        Map<String,Object>modelMap=new HashMap<>();
        long shopId=HttpServletRequestUtil.getLong(request,"shopId");
        if(shopId<0){
            Object currentShopObj=request.getSession().getAttribute("currentShop");
            if(currentShopObj==null){
                modelMap.put("redirect",true);
                modelMap.put("url","o2o/shop/shoplist");
            }else{
                Shop currentShop=(Shop)currentShopObj;
                modelMap.put("redirect",false);
                modelMap.put("shopId",currentShop.getShopId());
            }
        }else{
            Shop currentShop=new Shop();
            currentShop.setShopId(shopId);
            request.getSession().setAttribute("currentShop",currentShop);
            modelMap.put("redirect",false);
        }
        return ResultVOUtil.success(modelMap);
    }
}
























